#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from __future__ import division, unicode_literals

import os
import collections
from manager import mytool, models
from django.shortcuts import render, redirect
from django.contrib import messages
from datetime import datetime
from django.template import RequestContext
from django.conf import settings
from django.contrib.auth.decorators import login_required


@login_required(login_url='/login/')
def list_files(request):
    """　显示文档列表，并保存提交的文档　"""
    now = datetime.now()
    username = request.user.username
    dir_path = settings.MEDIA_ROOT

    # 获取文件列表，按时间倒序排
    sep = os.sep
    fs = collections.OrderedDict()
    _fs = os.listdir(dir_path)
    _fs = sorted(_fs,
                 key=lambda x: os.path.getctime(os.path.join(dir_path, x)),
                 reverse=True)

    for _f in _fs:
        _name = os.path.join(dir_path, _f)
        if not os.path.isfile(_name):
            continue

        timestamp = os.path.getctime(_name)
        fs[_f] = mytool.timestamp_to_time(timestamp)

    # 获取操作日志
    logs = models.DocLogModel.objects.all().order_by('-current_date')

    request_context = RequestContext(request)
    request_context.push(locals())
    return render(request, 'files/files.html', request_context)


@login_required(login_url='/login/')
def upload_file(request):
    """ 上传文档 """
    username = request.user.username
    dir_path = settings.MEDIA_ROOT

    if request.method == 'POST':

        up_file = request.FILES.get('up_file')
        if not up_file:
            messages.add_message(request, messages.WARNING,
                                 "请选择要上传的文件")
            return redirect('/files')

        file_path = os.path.join(dir_path, up_file.name)

        try:
            with open(file_path.encode('utf-8'), 'wb') as f:
                for chunk in up_file.chunks():
                    f.write(chunk)

        except Exception as e:
            messages.add_message(request, messages.WARNING,
                                 u"文档写入失败，请稍后再试。原因: {0}".format(e))
            return redirect('/files')

        else:
            # 上传文件操作写入日志
            doc_log = models.DocLogModel()
            doc_log.username = username
            _content = u"上传了文档【{0}】".format(up_file.name)
            doc_log.content = _content[0:98]
            doc_log.save()

            messages.add_message(request, messages.SUCCESS, "上传文档成功。")
            return redirect('/files')

    request_context = RequestContext(request)
    request_context.push(locals())
    return render(request, 'files/upload_file.html', request_context)
